package com.zf.shuashua.ui.gift;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;

import com.dhcw.sdk.BDAdvanceFloatIconAd;
import com.dhcw.sdk.BDAdvanceFloatIconListener;
import com.dhcw.sdk.BDAppNativeOnClickListener;
import com.duoyou.task.openapi.DyAdApi;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.XPopupCallback;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.tencent.bugly.beta.Beta;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.InteractionAdListener;
import com.zf.shuashua.advert.NativeAdvertManager;
import com.zf.shuashua.advert.OnRewardListener;
import com.zf.shuashua.advert.RewardAdvertManager;
import com.zf.shuashua.advert.RewardByteBxmManager;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BaseActivity1;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.BindWX;
import com.zf.shuashua.bean.Giftjson;
import com.zf.shuashua.bean.InviteJson;
import com.zf.shuashua.bean.JumpJson;
import com.zf.shuashua.bean.NationalBean;
import com.zf.shuashua.bean.ShareBean;
import com.zf.shuashua.bean.WithdrawJson;
import com.zf.shuashua.bean.WithdrawJsonTip1;
import com.zf.shuashua.helper.LoadDialogManager;
import com.zf.shuashua.manager.CalendarManager;
import com.zf.shuashua.manager.track.TrackConstants;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.ui.custom.RxBus;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.ui.mine.MineH5Activity;
import com.zf.shuashua.ui.popup.ActivityRulesPopup;
import com.zf.shuashua.ui.popup.ActivityRulesPopup1;
import com.zf.shuashua.ui.popup.BillFailPopup;
import com.zf.shuashua.ui.popup.BillFailPopup1;
import com.zf.shuashua.ui.popup.BillSuccessPopup;
import com.zf.shuashua.ui.popup.CommonPopup;
import com.zf.shuashua.ui.popup.IncomeExplainPopup;
import com.zf.shuashua.ui.popup.InviteFailPopup;
import com.zf.shuashua.ui.popup.InviteTipPopup;
import com.zf.shuashua.ui.popup.LackBalancePopup;
import com.zf.shuashua.ui.popup.NationalActivityPopup;
import com.zf.shuashua.ui.popup.NoticeTipDialog;
import com.zf.shuashua.ui.popup.OnPopupListener;
import com.zf.shuashua.ui.popup.OnWithdrawListener;
import com.zf.shuashua.ui.popup.PromoteActivePopup;
import com.zf.shuashua.ui.popup.RulesPopup;
import com.zf.shuashua.ui.popup.WithdrawBindPopup;
import com.zf.shuashua.ui.popup.WithdrawConfirmPopup;
import com.zf.shuashua.ui.popup.WithdrawPopup;
import com.zf.shuashua.ui.popup.WithdrawTip1Popup;
import com.zf.shuashua.ui.popup.WithdrawTip4Popup;
import com.zf.shuashua.utils.CommonConstants;
import com.zf.shuashua.utils.ConvertUtils;
import com.zf.shuashua.utils.NotificationUtil;
import com.zf.shuashua.utils.TextUtil;
import com.zf.shuashua.utils.ToNotification;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.utils.Util;
import com.zf.shuashua.utils.WebUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 *
 */
public class H5Activity extends BaseActivity1 {
    private String type = "";
    private String type1 = "";
    private WebView webview;
    private Toolbar mToolbar;
    private TextView mTvTitle;
    private TextView mTvRight;
    private RelativeLayout mRlContainer;
    private Disposable disposable;
    public static final int BING = 5;//
    private String url;
    private Intent intent;
    private boolean toNotify = false;//去设置通知开关
    private String mAdvertType = AdvertConstants.REWARD_TYPE_TASK;
    // 是否新手指引
    private boolean isGuide = false;
    private String cookieStr;
    private FrameLayout adContainer;

    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            String open_id = data.get("uid");
            if (open_id == null) {
                open_id = "";
            }
            String nick_name = data.get("name");
            if (nick_name == null) {
                nick_name = "";
            }
            String avatar = data.get("iconurl");
            if (avatar == null) {
                avatar = "";
            }
            String sex = data.get("gender");
            if (sex == null) {
                sex = "";
            }
            String city = data.get("city");
            if (city == null) {
                city = "";
            }
            if (SHARE_MEDIA.QQ == platform) {
                type = "qq";
                type1 = AdvertConstants.REWARD_TYPE_BIND_QQ;
            } else if (SHARE_MEDIA.SINA == platform) {
                type = "weibo";
                type1 = AdvertConstants.REWARD_TYPE_BIND_WEIBO;
            } else if (SHARE_MEDIA.WEIXIN == platform) {
                if (isActivityEnable()) {
                    LoadDialogManager.getInstance().show(H5Activity.this);
                }
                type = "wechat";
                type1 = AdvertConstants.REWARD_TYPE_BIND;
                open_id = data.get("openid");
                if (open_id == null) {
                    open_id = "";
                }
            }
            HttpData.getInstance().bindThird(type, open_id, nick_name, avatar, sex, city, "", "", "", "", new ACallback<BindWX>() {
                @Override
                public void onSuccess(BindWX data) {
                    LoadDialogManager.getInstance().dismiss();
                    if (data != null) {
                        if (data.isStatus()) {
                            ToastUtil.show(H5Activity.this, data.getData() + "");
                            quickCallJs("taskResult", null, type1, "true");
                            if (SHARE_MEDIA.WEIXIN == platform) {
                                ShuaApplication.is_bind_wechat = true;
                            }
                        } else {
                            ToastUtil.show(H5Activity.this, data.getMessage() + "");
                        }
                    }
                }

                @Override
                public void onFail(int errCode, String errMsg) {
                    LoadDialogManager.getInstance().dismiss();
                    ToastUtil.showToast(H5Activity.this, "绑定失败,请重试");
                }
            });
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            LoadDialogManager.getInstance().dismiss();
            Toast.makeText(H5Activity.this, t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            LoadDialogManager.getInstance().dismiss();
            Toast.makeText(H5Activity.this, "绑定取消了", Toast.LENGTH_LONG).show();
        }
    };
    private String title;


    public boolean isActivityEnable() {
        if (isDestroyed() || isFinishing()) {
            return false;
        }
        return true;
    }

    @Override
    protected void initView() {
        webview = findViewById(R.id.web);
        mToolbar = findViewById(R.id.toolbar);
        mTvTitle = findViewById(R.id.tv_title);
        mTvRight = findViewById(R.id.tv_right);
        adContainer = findViewById(R.id.fl_ad_container);
        intent = getIntent();
        title = intent.getStringExtra("title");
        url = intent.getStringExtra("money");
        mTvTitle.setText(title);
        mToolbar.setTitle("");
        if ("我的钱包".equals(title)) {
            mTvRight.setText("账户流水");
        } else if ("账户流水".equals(title)) {
            mTvRight.setText("审核进度");
        } else if ("邀请好友".equals(title)) {
            mTvRight.setText("活动规则");
        } else if (url.contains("activity_national_day")) {
            mTvRight.setText("活动规则");
        }

        if (intent.hasExtra("is_guide")) {
            isGuide = intent.getBooleanExtra("is_guide", false);
        }
        setSupportActionBar(mToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initWebView();
        setCookie(Constants.H5_URL, "showHeader=0");
        loadUrl();
        disposable = RxBus.getInstance().toObservable(BindWX.class).subscribe(bingWX -> {
            if (bingWX.isStatus()) {
                webview.evaluateJavascript("javascript:updatePage()", null);
            }

        });
        if ("我的钱包".equals(title)) {
            mTvRight.setOnClickListener(view -> startActivity(new Intent(H5Activity.this, H5Activity.class).putExtra("money", Constants.H5_URL + "wallet").putExtra("title", "账户流水")));
        } else if ("账户流水".equals(title)) {
            mTvRight.setOnClickListener(view -> startActivity(
                    new Intent(H5Activity.this, H5Activity.class)
                            .putExtra("money", Constants.H5_URL + "schedule")
                            .putExtra("title", "审核进度")));
        } else if ("邀请好友".equals(title)) {
            mTvRight.setOnClickListener(view -> shouActivity());
        } else if (url.contains("activity_national_day")) {
            mTvRight.setOnClickListener(view -> shouActivity1());
        } else {
            mTvRight.setVisibility(View.GONE);
        }
        checkBxmAd();
    }

    private void checkBxmAd(){
        if("我的钱包".equals(title)){
            loadAd();
        }
    }

    /**
     * 为指定的url添加cookie
     *
     * @param url           url
     * @param cookieContent cookie内容
     */
    private void setCookie(String url, String cookieContent) {
        CookieManager cm = CookieManager.getInstance();
        CookieSyncManager csm = CookieSyncManager.createInstance(this);
        cm.setAcceptCookie(true);
        cm.setCookie(url, cookieContent);

       /* //api21以上提供了回调接口来确认cookie是否设置成功
        cm.setCookie(url, cookieContent, new ValueCallback<Boolean>() {
            @Override
            public void onReceiveValue(Boolean value) {
            }
        });*/
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            cm.flush();
        } else {
            csm.sync();
        }
    }


    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void initWebView() {
        WebSettings ws = webview.getSettings();
        // 网页内容的宽度是否可大于WebView控件的宽度
        ws.setLoadWithOverviewMode(false);
        // 保存表单数据
        ws.setSaveFormData(true);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        ws.setSupportZoom(true);
        ws.setBuiltInZoomControls(true);
        ws.setDisplayZoomControls(false);
        // 启动应用缓存
        ws.setAppCacheEnabled(true);
        // 设置缓存模式
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
        ws.setUseWideViewPort(true);
        // 不缩放
        webview.setInitialScale(100);
        // 告诉WebView启用JavaScript执行。默认的是false。
        ws.setJavaScriptEnabled(true);
        //  页面加载好以后，再放开图片
        ws.setBlockNetworkImage(false);
        // 使用localStorage则必须打开
        ws.setDomStorageEnabled(true);
        // 排版适应屏幕
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // WebView是否新窗口打开(加了后可能打不开网页)
//        ws.setSupportMultipleWindows(true);

        // webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        /** 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用)*/
        ws.setTextZoom(100);

//        mWebChromeClient = new MyWebChromeClient(this);
//        webview.setWebChromeClient(mWebChromeClient);
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String tit) {
                super.onReceivedTitle(view, tit);
                if (TextUtils.isEmpty(title) && !TextUtils.isEmpty(tit)) {
                    mTvTitle.setText(tit);
                }
            }
        });
        // 与js交互
        webview.addJavascriptInterface(H5Activity.this, "android");
        webview.addJavascriptInterface(new JSInterface(), "wx");
        webview.setWebViewClient(new WebViewClient() {//新手提现步骤
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            @Override
            public void onPageFinished(WebView view, String url) {
//                if (GuideEntity.isGuide && isGuide) {
//                    GuideEntity.isGuide = false;
//                    isGuide = false;
//                    WithdrawJsonTip1 tip1 = new WithdrawJsonTip1();
//                    WithdrawJson1 withdrawJson1 = new WithdrawJson1();
//                    withdrawJson1.setIs_finish(true);
//                    withdrawJson1.setTask("完成新手任务");
//                    withdrawJson1.setValue("0.3");
//                    withdrawJson1.setFlag(1);
//                    withdrawJson1.setTaskType("task");
//                    tip1.setCurCashTaskInfo(withdrawJson1);
//                    PopViewWithdrawEvent(ParseJsonUtils.toJson(tip1));
//                    // 请求新手指导完成接口
//                    HttpData.getInstance().postUserGuide(new ACallback<String>() {
//                        @Override
//                        public void onSuccess(String data) {
//                        }
//
//                        @Override
//                        public void onFail(int errCode, String errMsg) {
//                        }
//                    });
//                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

    }

    //活动规则弹框
    public void shouActivity() {
        ActivityRulesPopup activityRulesPopup = new ActivityRulesPopup(H5Activity.this);
        new XPopup.Builder(H5Activity.this)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .setPopupCallback(new XPopupCallback() {
                    @Override
                    public void onCreated() {

                    }

                    @Override
                    public void beforeShow() {

                    }

                    @Override
                    public void onShow() {
                        NativeAdvertManager.getInstance().loadExpressAd(H5Activity.this, 270, new InteractionAdListener() {
                            @Override
                            public void onRenderSuccess(View view) {
                                activityRulesPopup.addAdvertView(view);
                            }

                            @Override
                            public void onError() {
                                activityRulesPopup.loadAdvertFail();
                            }
                        });
                    }

                    @Override
                    public void onDismiss() {

                    }

                    @Override
                    public boolean onBackPressed() {
                        return false;
                    }
                })
                .asCustom(activityRulesPopup)
                .show();

    }

    //活动规则弹框
    public void shouActivity1() {
        ActivityRulesPopup1 activityRulesPopup = new ActivityRulesPopup1(H5Activity.this);
        new XPopup.Builder(H5Activity.this)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .setPopupCallback(new XPopupCallback() {
                    @Override
                    public void onCreated() {

                    }

                    @Override
                    public void beforeShow() {

                    }

                    @Override
                    public void onShow() {
                        NativeAdvertManager.getInstance().loadExpressAd(H5Activity.this, 270, new InteractionAdListener() {
                            @Override
                            public void onRenderSuccess(View view) {
                                activityRulesPopup.addAdvertView(view);
                            }

                            @Override
                            public void onError() {
                                activityRulesPopup.loadAdvertFail();
                            }
                        });
                    }

                    @Override
                    public void onDismiss() {

                    }

                    @Override
                    public boolean onBackPressed() {
                        return false;
                    }
                })
                .asCustom(activityRulesPopup)
                .show();

    }

    public void loadUrl() {
        if (webview != null && !TextUtils.isEmpty(url)) {
            webview.loadUrl(url);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_h5;
    }

    BDAdvanceFloatIconAd bdAdvanceFloatIconAd;
    private void loadAd() {
        if(!ShuaApplication.isBxmOpen()){
            return;
        }
        adContainer.setVisibility(View.VISIBLE);
        bdAdvanceFloatIconAd = new BDAdvanceFloatIconAd(this, adContainer, "807272001003");
        bdAdvanceFloatIconAd.setBdAdvanceFloatIconListener(new BDAdvanceFloatIconListener() {
            @Override
            public void onActivityClosed() {
//                Toast.makeText(getApplicationContext(), "活动页关闭 ", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onAdShow() {
//                Toast.makeText(getApplicationContext(), "广告展示 ", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onAdFailed() {
//                Toast.makeText(getApplicationContext(), "广告加载失败 ", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onAdClicked() {
//                Toast.makeText(getApplicationContext(), "广告点击 ", Toast.LENGTH_LONG).show();
            }
        });
        bdAdvanceFloatIconAd.setBdAppNativeOnClickListener(new BDAppNativeOnClickListener() {
            @Override
            public void onActivityClosed() {
//                Toast.makeText(getApplicationContext(), "float onActivityClosed ", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onClick(int type, String adid) {
                //type=1 加载视频   type=2 播放视频
                if(type==1){
                    //bdAdvanceFloatIconAd 绑定激励视频回调
                    RewardByteBxmManager.getInstance().load(H5Activity.this, bdAdvanceFloatIconAd);
                }else if(type==2){
                    RewardByteBxmManager.getInstance().play(H5Activity.this);
                }

            }
        });
        bdAdvanceFloatIconAd.loadAd();
    }

    //分享
    private class JSInterface {
        //微信
        @JavascriptInterface
        public void shareToWx(String jsonString) {
            getDomain(SHARE_MEDIA.WEIXIN, jsonString);
        }

        //QQ
        @JavascriptInterface
        public void shareToQQ(String jsonString) {
            runOnUiThread(() -> {
                if (PermissionsUtil.hasPermission(H5Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    //有访问摄像头的权限
                    getDomain(SHARE_MEDIA.QQ, jsonString);
                } else {
                    PermissionsUtil.requestPermission(H5Activity.this, new PermissionListener() {
                        @Override
                        public void permissionGranted(@NonNull String[] permissions) {
                            //用户授予了
                            getDomain(SHARE_MEDIA.QQ, jsonString);
                        }

                        @Override
                        public void permissionDenied(@NonNull String[] permissions) {
                            //用户拒绝了
                        }
                    }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
                }
            });
        }

        //微博
        @JavascriptInterface
        public void shareToSINA(String jsonString) {
            runOnUiThread(() -> {
                getDomain(SHARE_MEDIA.SINA, jsonString);
            });
        }

        //QQ空间
        @JavascriptInterface
        public void shareToQZONE(String jsonString) {
            runOnUiThread(() -> {
                if (PermissionsUtil.hasPermission(H5Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    //有访问摄像头的权限
                    getDomain(SHARE_MEDIA.QZONE, jsonString);
                } else {
                    PermissionsUtil.requestPermission(H5Activity.this, new PermissionListener() {
                        @Override
                        public void permissionGranted(@NonNull String[] permissions) {
                            //用户授予了
                            getDomain(SHARE_MEDIA.QZONE, jsonString);
                        }

                        @Override
                        public void permissionDenied(@NonNull String[] permissions) {
                            //用户拒绝了
                        }
                    }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
                }
            });
        }

        //微信盆友圈
        @JavascriptInterface
        public void shareToWEIXIN_CIRCLE(String jsonString) {
            runOnUiThread(() -> {
                getDomain(SHARE_MEDIA.WEIXIN_CIRCLE, jsonString);
            });
        }

        //面对面扫码
        @JavascriptInterface
        public void shareToScan(String jsonString) {
            LogUtil.d(jsonString);
            startActivity(new Intent(H5Activity.this, MineH5Activity.class).putExtra("money", Constants.H5_URL + "facetoface").putExtra("title", "面对面邀请"));
        }

        //绑定微信
        @JavascriptInterface
        public void toBingWX() {
            runOnUiThread(() -> {
                UMShareConfig config = new UMShareConfig();
                config.isNeedAuthOnGetUserInfo(true);
                UMShareAPI.get(H5Activity.this).setShareConfig(config);
                if (UMShareAPI.get(H5Activity.this).isInstall(H5Activity.this, SHARE_MEDIA.WEIXIN)) {
                    UMShareAPI.get(H5Activity.this).getPlatformInfo(H5Activity.this, SHARE_MEDIA.WEIXIN, authListener);
                } else {
                    Toast.makeText(H5Activity.this, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
                }
            });
        }

        /**
         * 复制字符串
         *
         * @param context
         * @param text
         */
        private void toCopy(Context context, String text) {
            ClipboardManager mClipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            mClipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));
        }
    }

    //打开微信
    @JavascriptInterface
    public void openWeChat() {
        if (UMShareAPI.get(H5Activity.this).isInstall(H5Activity.this, SHARE_MEDIA.WEIXIN)) {
            TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_TASK_INVITE_ZHANTIE, TrackConstants.NOTE_TASK_INVITE_ZHANTIE);
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName cn = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.setComponent(cn);
            startActivity(intent);
        } else {
            Toast.makeText(H5Activity.this, "您没有安装微信，请先安装", Toast.LENGTH_SHORT).show();
        }
    }

    //微信盆友圈
    @JavascriptInterface
    public void shareImageToWechatTimeLine(String base64Img) {
        runOnUiThread(() -> {
            try {
                Bitmap bitmap = ConvertUtils.base64ToBitmap(base64Img);
                UMImage image = new UMImage(H5Activity.this, bitmap);
                image.setThumb(new UMImage(H5Activity.this, R.mipmap.share_icon));  //缩略图
                new ShareAction(H5Activity.this)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                        .withMedia(image)
                        .setCallback(shareListener)
                        .share();
            } catch (Exception ignored) {

            }
        });
    }

    @JavascriptInterface
    public String getBlackBox() {
        return ShuaApplication.blackbox;
    }

    @JavascriptInterface
    public String getToken() {
        return ShuaApplication.token;
    }

    @JavascriptInterface
    public String getDeviceId() {
        if (!Store.getInstance().getPrivacy()) {
            return "";
        }
        return Util.getDeviceId(ShuaApplication.getContext());
    }

    @JavascriptInterface
    public String getAccessToken() {
        return ShuaApplication.accessToken;
    }

    @JavascriptInterface
    public String getChannel() {
        return ShuaApplication.channel;
    }

    @JavascriptInterface
    public void openHome() {
        setResult(RESULT_OK);
        finish();
    }

    @JavascriptInterface
    public void openGame() {
        if (!ToLogin()) {
            /**
             * userId : 用户uid
             * advertType: 0（默认值）显示全部数据  1.手游  2.棋牌游戏
             */
            DyAdApi.getDyAdApi().jumpAdList(this, Store.getInstance().getuserId(), 0);
        }
    }

    @JavascriptInterface
    public void logout() {
        Store.getInstance().logoutFromH5Page(this);
        finish();
    }

    @JavascriptInterface
    public String getAppVersion() {
        return getVersionName();
    }

    @JavascriptInterface
    public String getSystemModel() {
        if (!Store.getInstance().getPrivacy()) {
            return "";
        }
        return android.os.Build.MODEL;
    }

    @JavascriptInterface
    public String getApiVersion() {
        return CommitUtils.API_VERSION;
    }

    //to提现
    @JavascriptInterface
    public void toWithdraw() {
        startActivityForResult(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + "withdraw").putExtra("title", "我的钱包"), CommonConstants.MAIN);
    }

    //to绑定银行卡
    @JavascriptInterface
    public void toBindCard() {
        startActivityForResult(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + "bindCard").putExtra("title", "个人信息验证"), BING);
    }

    //to关闭当前页面
    @JavascriptInterface
    public void toFinish() {
        setResult(RESULT_OK);
        finish();
    }

    @JavascriptInterface
    public void login() {
        Intent intent = new Intent(H5Activity.this, LoginActivity.class);
        startActivity(intent);
    }

    //收益说明
    @JavascriptInterface
    public void IncomeExplainHelpEvent() {
        runOnUiThread(() -> {
            Activity activity = this;
            IncomeExplainPopup explainPopup = new IncomeExplainPopup(this);
            new XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .setPopupCallback(new XPopupCallback() {
                        @Override
                        public void onCreated() {

                        }

                        @Override
                        public void beforeShow() {

                        }

                        @Override
                        public void onShow() {
                            NativeAdvertManager.getInstance().loadExpressAd(activity, 270, new InteractionAdListener() {
                                @Override
                                public void onRenderSuccess(View view) {
                                    explainPopup.addAdvertView(view);
                                }

                                @Override
                                public void onError() {
                                    explainPopup.loadAdvertFail();
                                }
                            });
                        }

                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public boolean onBackPressed() {
                            return false;
                        }
                    })
                    .asCustom(explainPopup)
                    .show();
        });
    }

    //提升活跃度
    @JavascriptInterface
    public void PromoteActiveHelpEvent() {
        runOnUiThread(() -> {
            Activity activity = this;
            PromoteActivePopup activePopup = new PromoteActivePopup(this);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false)
                    .setPopupCallback(new XPopupCallback() {
                        @Override
                        public void onCreated() {

                        }

                        @Override
                        public void beforeShow() {

                        }

                        @Override
                        public void onShow() {
                            NativeAdvertManager.getInstance().loadExpressAd(activity, 270, new InteractionAdListener() {
                                @Override
                                public void onRenderSuccess(View view) {
                                    activePopup.addAdvertView(view);
                                }

                                @Override
                                public void onError() {
                                    activePopup.loadAdvertFail();
                                }
                            });
                        }

                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public boolean onBackPressed() {
                            return false;
                        }
                    })
                    .asCustom(activePopup)
                    .show();
        });
    }

    //跳转到h5的次级界面
    @JavascriptInterface
    public void redirectEvent(String uri, String title) {
        startActivityForResult(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + uri).putExtra("title", title), CommonConstants.MAIN);
    }

    @JavascriptInterface
    public void loadWebEvent(String url, String title) {
        startActivityForResult(new Intent(this, H5Activity.class).putExtra("money", url).putExtra("title", title), CommonConstants.MAIN);
    }

    /**
     * 跳转到指定界面
     *
     * @param data json格式，{"type": "home"}
     *             "home":视频首页；"task":任务；"friend":邀请好友；"xdraw":提现；"hot_share";热点视频分享；"turntable":大转盘；"jiangchi":奖池
     */
    @JavascriptInterface
    public void jumpEvent(String data) {
        runOnUiThread(() -> {
            if (TextUtils.isEmpty(data)) {
                return;
            }
            JumpJson result = ParseJsonUtils.parseData(data + "", JumpJson.class);
            if (result == null) {
                return;
            }
            finish();
            EventBus.getDefault().post(result);
        });
    }

    //获取通知栏权限是否已经开启
    @JavascriptInterface
    public boolean isNotifyEnabled() {
        return NotificationUtil.isNotifyEnabled(H5Activity.this);
//        webview.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                quickCallJs("taskResult", null, AdvertConstants.REWARD_TYPE_NOTIFICATION, NotificationUtil.isNotifyEnabled(H5Activity.this) + "");
//            }
//        }, 100);
    }

    //去开启通知
    @JavascriptInterface
    public void toNotify() {
        runOnUiThread(() -> {
            toNotify = true;
            ToNotification.open(H5Activity.this);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (toNotify) {
            quickCallJs("taskResult", null, AdvertConstants.REWARD_TYPE_NOTIFICATION, NotificationUtil.isNotifyEnabled(H5Activity.this) + "");
            toNotify = false;
        }
    }

    private void showNoticeTip() {
        boolean isEnable = NotificationUtil.isNotifyEnabled(this);
        if (isEnable) {
            return;
        }
        NoticeTipDialog noticeTipDialog = new NoticeTipDialog(this);
        noticeTipDialog.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_MY_TIXIAN_OPEN, TrackConstants.NOTE_MY_TIXIAN_OPEN);
                ToNotification.open(H5Activity.this);
            }

            @Override
            public void onClose() {
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_MY_TIXIAN_OFF, TrackConstants.NOTE_MY_TIXIAN_OFF);

            }
        });
        noticeTipDialog.show();
    }

    //提现成功/失败
    @JavascriptInterface
    public void WithdrawResultEvent(String data) {
        runOnUiThread(() -> {
            WithdrawJson result = ParseJsonUtils.parseData(data + "", WithdrawJson.class);
            if (result == null) {
                return;
            }
            Activity activity = this;
            if (result.isSuccess()) {
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_MY_TIXIAN_SUCCEED, TrackConstants.NOTE_MY_TIXIAN_SUCCEED);
                BillSuccessPopup activePopup = new BillSuccessPopup(this, result.isNewUser());
                activePopup.setPopupListener(new OnPopupListener() {
                    @Override
                    public void onNext() {
                        dealWithdraw("home", "");
                    }

                    @Override
                    public void onClose() {

                    }
                });
                new XPopup.Builder(this)
                        .dismissOnBackPressed(false)
                        .dismissOnTouchOutside(false)
                        .setPopupCallback(new XPopupCallback() {
                            @Override
                            public void onCreated() {

                            }

                            @Override
                            public void beforeShow() {

                            }

                            @Override
                            public void onShow() {
                                NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                                    @Override
                                    public void onRenderSuccess(View view) {
                                        activePopup.addAdvertView(view);
                                    }

                                    @Override
                                    public void onError() {
                                        activePopup.loadAdvertFail();
                                    }
                                });
                            }

                            @Override
                            public void onDismiss() {

                            }

                            @Override
                            public boolean onBackPressed() {
                                return false;
                            }
                        })
                        .asCustom(activePopup)
                        .show();
            } else {
                if (result.getMessage().contains("TIPS")) {
                    new XPopup.Builder(this)
                            .dismissOnTouchOutside(false)
                            .dismissOnBackPressed(false)
                            .asCustom(new BillFailPopup1(this, result.getMessage()))
                            .show();

                } else {
                    BillFailPopup activePopup = new BillFailPopup(this, result.getMessage());
                    activePopup.setPopupListener(new OnPopupListener() {
                        @Override
                        public void onNext() {
                            dealWithdraw("home", "");
                        }

                        @Override
                        public void onClose() {

                        }
                    });
                    new XPopup.Builder(this)
                            .dismissOnTouchOutside(false)
                            .dismissOnBackPressed(false)
                            .setPopupCallback(new XPopupCallback() {
                                @Override
                                public void onCreated() {

                                }

                                @Override
                                public void beforeShow() {

                                }

                                @Override
                                public void onShow() {
                                    NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                                        @Override
                                        public void onRenderSuccess(View view) {
                                            activePopup.addAdvertView(view);
                                        }

                                        @Override
                                        public void onError() {
                                            activePopup.loadAdvertFail();
                                        }
                                    });
                                }

                                @Override
                                public void onDismiss() {

                                }

                                @Override
                                public boolean onBackPressed() {
                                    return false;
                                }
                            })
                            .asCustom(activePopup)
                            .show();
                }
            }

        });
    }

    private void dealWithdraw(String taskType, String comeFrom) {
        if (!TextUtils.isEmpty(comeFrom)) {
            taskType = "task";
        }
        Intent intent = new Intent();
        intent.putExtra("taskType", taskType);
        setResult(RESULT_OK, intent);
        finish();
    }

    //余额不足
    @JavascriptInterface
    public void PopLackBalanceEvent(String data) {
        runOnUiThread(() -> {
            if (isPopWithdrawShowing) {
                return;
            }
            isPopWithdrawShowing = true;
            if (webview != null) {
                webview.postDelayed(() -> isPopWithdrawShowing = false, 1000);
            } else {
                isPopWithdrawShowing = false;
            }
            if (!checkBindWechat()) {
                return;
            }
            Activity activity = this;
            LackBalancePopup activePopup = new LackBalancePopup(this);
            new XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .setPopupCallback(new XPopupCallback() {
                        @Override
                        public void onCreated() {

                        }

                        @Override
                        public void beforeShow() {

                        }

                        @Override
                        public void onShow() {
                            NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                                @Override
                                public void onRenderSuccess(View view) {
                                    activePopup.addAdvertView(view);
                                }

                                @Override
                                public void onError() {
                                    activePopup.loadAdvertFail();
                                }
                            });
                        }

                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public boolean onBackPressed() {
                            return false;
                        }
                    })
                    .asCustom(activePopup)
                    .show();
        });
    }

    private boolean isPopWithdrawShowing;

    //点击提现金额
    @JavascriptInterface
    public void PopViewWithdrawEvent(String data) {
        runOnUiThread(() -> {
            if (isPopWithdrawShowing) {
                return;
            }
            isPopWithdrawShowing = true;
            if (webview != null) {
                webview.postDelayed(() -> isPopWithdrawShowing = false, 1000);
            } else {
                isPopWithdrawShowing = false;
            }
            if (!checkBindWechat()) {
                return;
            }
            WithdrawJsonTip1 withdrawJson1 = ParseJsonUtils.parseData(data + "", WithdrawJsonTip1.class);
            String comeFrom;
            String taskType;
            Activity activity = this;
            comeFrom = withdrawJson1.getComeFrom();
            taskType = withdrawJson1.getCurCashTaskInfo().getTaskType();
            int flag = withdrawJson1.getCurCashTaskInfo().getFlag();
            if (flag == 1) {
                WithdrawTip4Popup activePopup = new WithdrawTip4Popup(this, withdrawJson1.getCurCashTaskInfo());
                activePopup.setPopupListener(new OnWithdrawListener() {
                    @Override
                    public void onNext() {
                        quickCallJs("TaskFinishedCallbackEvent", null, data);
                    }

                    @Override
                    public void onClose() {

                    }

                    @Override
                    public void toFinish(String value) {
                        quickCallJs("TaskNextCallbackEvent", null, data);
                    }
                });
                new XPopup.Builder(this)
                        .dismissOnBackPressed(false)
                        .dismissOnTouchOutside(false)
                        .setPopupCallback(new XPopupCallback() {
                            @Override
                            public void onCreated() {

                            }

                            @Override
                            public void beforeShow() {

                            }

                            @Override
                            public void onShow() {
                                NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                                    @Override
                                    public void onRenderSuccess(View view) {
                                        activePopup.addAdvertView(view);
                                    }

                                    @Override
                                    public void onError() {
                                        activePopup.loadAdvertFail();
                                    }
                                });
                            }

                            @Override
                            public void onDismiss() {

                            }

                            @Override
                            public boolean onBackPressed() {
                                return false;
                            }
                        })
                        .asCustom(activePopup)
                        .show();
            } else {
                WithdrawTip1Popup activePopup = new WithdrawTip1Popup(this, withdrawJson1.getCurCashTaskInfo());
                activePopup.setPopupListener(new OnWithdrawListener() {
                    @Override
                    public void onNext() {
                        quickCallJs("TaskFinishedCallbackEvent", null, data);
                    }

                    @Override
                    public void onClose() {

                    }

                    @Override
                    public void toFinish(String value) {
                        dealWithdraw(taskType, comeFrom);
                    }
                });
                new XPopup.Builder(this)
                        .dismissOnBackPressed(false)
                        .dismissOnTouchOutside(false)
                        .setPopupCallback(new XPopupCallback() {
                            @Override
                            public void onCreated() {

                            }

                            @Override
                            public void beforeShow() {

                            }

                            @Override
                            public void onShow() {
                                NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                                    @Override
                                    public void onRenderSuccess(View view) {
                                        activePopup.addAdvertView(view);
                                    }

                                    @Override
                                    public void onError() {
                                        activePopup.loadAdvertFail();
                                    }
                                });
                            }

                            @Override
                            public void onDismiss() {

                            }

                            @Override
                            public boolean onBackPressed() {
                                return false;
                            }
                        })
                        .asCustom(activePopup)
                        .show();
            }
        });
    }

    //补填邀请码提示
    @JavascriptInterface
    public void PopInviteCodeMessageEvent(String data) {
        runOnUiThread(() -> {
            InviteJson result = ParseJsonUtils.parseData(data + "", InviteJson.class);
            if (result == null) {
                return;
            }
            Activity activity = this;
            if (result.getUiType() == 1) {
                InviteTipPopup activePopup = new InviteTipPopup(this);
                activePopup.setPopupListener(new OnPopupListener() {
                    @Override
                    public void onNext() {
                        finish();
                    }

                    @Override
                    public void onClose() {

                    }
                });
                new XPopup.Builder(this)
                        .dismissOnBackPressed(false)
                        .dismissOnTouchOutside(false)
                        .setPopupCallback(new XPopupCallback() {
                            @Override
                            public void onCreated() {

                            }

                            @Override
                            public void beforeShow() {

                            }

                            @Override
                            public void onShow() {
                                NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_COMMON, 270, new InteractionAdListener() {
                                    @Override
                                    public void onRenderSuccess(View view) {
                                        activePopup.addAdvertView(view);
                                    }

                                    @Override
                                    public void onError() {
                                        activePopup.loadAdvertFail();
                                    }
                                });
                            }

                            @Override
                            public void onDismiss() {

                            }

                            @Override
                            public boolean onBackPressed() {
                                return false;
                            }
                        })
                        .asCustom(activePopup)
                        .show();
            } else {
                InviteFailPopup activePopup = new InviteFailPopup(this, result.getMessage());
                new XPopup.Builder(this)
                        .dismissOnTouchOutside(false)
                        .dismissOnBackPressed(false)
                        .setPopupCallback(new XPopupCallback() {
                            @Override
                            public void onCreated() {

                            }

                            @Override
                            public void beforeShow() {

                            }

                            @Override
                            public void onShow() {
                                NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_COMMON, 270, new InteractionAdListener() {
                                    @Override
                                    public void onRenderSuccess(View view) {
                                        activePopup.addAdvertView(view);
                                    }

                                    @Override
                                    public void onError() {
                                        activePopup.loadAdvertFail();
                                    }
                                });
                            }

                            @Override
                            public void onDismiss() {

                            }

                            @Override
                            public boolean onBackPressed() {
                                return false;
                            }
                        })
                        .asCustom(activePopup)
                        .show();
            }
        });
    }

    private boolean ToLogin() {
        if (!Store.getInstance().isLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    private boolean checkBindWechat() {
        if (ShuaApplication.is_bind_wechat) {
            return true;
        }
        withdrawBind("");
        return false;
    }

    //提现方式
    @JavascriptInterface
    public void WithdrawEvent(String data) {
        runOnUiThread(() -> {
            if (!checkBindWechat()) {
                return;
            }
            Activity activity = this;
            WithdrawPopup popup = new WithdrawPopup(this);
            popup.setPopupListener(new OnPopupListener() {
                @Override
                public void onNext() {
                    if (ShuaApplication.is_bind_wechat) {
                        withdrawConfirm(data);
                    } else {
                        withdrawBind(data);
                    }
                }

                @Override
                public void onClose() {

                }
            });
            new XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .setPopupCallback(new XPopupCallback() {
                        @Override
                        public void onCreated() {

                        }

                        @Override
                        public void beforeShow() {

                        }

                        @Override
                        public void onShow() {
                            NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                                @Override
                                public void onRenderSuccess(View view) {
                                    popup.addAdvertView(view);
                                }

                                @Override
                                public void onError() {
                                    popup.loadAdvertFail();
                                }
                            });
                        }

                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public boolean onBackPressed() {
                            return false;
                        }
                    })
                    .asCustom(popup)
                    .show();
        });
    }

    //提现确认
    private void withdrawConfirm(String data) {
        Activity activity = this;
        WithdrawConfirmPopup popup = new WithdrawConfirmPopup(this);
        popup.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                quickCallJs("WithdrawCallbackEvent", null, data);
            }

            @Override
            public void onClose() {

            }
        });
        new XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .setPopupCallback(new XPopupCallback() {
                    @Override
                    public void onCreated() {

                    }

                    @Override
                    public void beforeShow() {

                    }

                    @Override
                    public void onShow() {
                        NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                            @Override
                            public void onRenderSuccess(View view) {
                                popup.addAdvertView(view);
                            }

                            @Override
                            public void onError() {
                                popup.loadAdvertFail();
                            }
                        });
                    }

                    @Override
                    public void onDismiss() {

                    }

                    @Override
                    public boolean onBackPressed() {
                        return false;
                    }
                })
                .asCustom(popup)
                .show();
    }

    //提现-绑定微信
    private void withdrawBind(String data) {
        Activity activity = this;
        WithdrawBindPopup popup = new WithdrawBindPopup(this);
        popup.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                popup.dismiss();
                toBingWX();
            }

            @Override
            public void onClose() {

            }
        });
        new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .setPopupCallback(new XPopupCallback() {
                    @Override
                    public void onCreated() {

                    }

                    @Override
                    public void beforeShow() {

                    }

                    @Override
                    public void onShow() {
                        NativeAdvertManager.getInstance().loadExpressAd(activity, 270, new InteractionAdListener() {
                            @Override
                            public void onRenderSuccess(View view) {
                                popup.addAdvertView(view);
                            }

                            @Override
                            public void onError() {
                                popup.loadAdvertFail();
                            }
                        });
                    }

                    @Override
                    public void onDismiss() {

                    }

                    @Override
                    public boolean onBackPressed() {
                        return false;
                    }
                })
                .asCustom(popup)
                .show();
    }

    //绑定微信
    @JavascriptInterface
    public void toBingWX() {
        runOnUiThread(() -> {
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI.get(H5Activity.this).setShareConfig(config);
            if (UMShareAPI.get(H5Activity.this).isInstall(H5Activity.this, SHARE_MEDIA.WEIXIN)) {
                UMShareAPI.get(H5Activity.this).getPlatformInfo(H5Activity.this, SHARE_MEDIA.WEIXIN, authListener);
            } else {
                Toast.makeText(H5Activity.this, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //活动规则
    @JavascriptInterface
    public void openTask() {
        runOnUiThread(() -> {
            Activity activity = this;
            RulesPopup popup = new RulesPopup(this);
            popup.setPopupListener(new OnPopupListener() {
                @Override
                public void onNext() {
                    HttpData.getInstance().getSwitch(1, new ACallback<BaseData>() {
                        @Override
                        public void onSuccess(BaseData data) {
                            LogUtil.d(data.getCode() + "");
                            if (data.isStatus()) {
                                quickCallJs("taskResult", null, "OPEN_TASK", "true");
                            }
                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            LogUtil.d(errMsg + "");


                        }
                    });


                }

                @Override
                public void onClose() {

                }
            });
            new XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .setPopupCallback(new XPopupCallback() {
                        @Override
                        public void onCreated() {

                        }

                        @Override
                        public void beforeShow() {

                        }

                        @Override
                        public void onShow() {
                            NativeAdvertManager.getInstance().loadExpressAd(activity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                                @Override
                                public void onRenderSuccess(View view) {
                                    popup.addAdvertView(view);
                                }

                                @Override
                                public void onError() {
                                    popup.loadAdvertFail();
                                }
                            });
                        }

                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public boolean onBackPressed() {
                            return false;
                        }
                    })
                    .asCustom(popup)
                    .show();
        });
    }

    //关闭回调：PopNationDayCallbackEvent，传jsonString
    //type: startNow：“立即开始”；dayReward：1号到7号的奖励弹窗；giftReward：8号的礼品奖励

    //国庆
    @JavascriptInterface
    public void PopNationDayEvent(String jsonString) {
        runOnUiThread(() -> {
            if (isPopWithdrawShowing) {
                return;
            }
            isPopWithdrawShowing = true;
            if (webview != null) {
                webview.postDelayed(() -> isPopWithdrawShowing = false, 1000);
            } else {
                isPopWithdrawShowing = false;
            }
            NationalBean result = ParseJsonUtils.parseData(jsonString + "", NationalBean.class);
            NationalActivityPopup nationalActivityPopup = new NationalActivityPopup(H5Activity.this, result.getType(), result.getTitle(), result.getContent1(), result.getContent2(), result.getContent3(), result.getContent4(), result.getBtnContent());
            nationalActivityPopup.setPopupListener(new OnPopupListener() {
                @Override
                public void onNext() {
                    PopNationDayCallbackEvent(jsonString);
                }

                @Override
                public void onClose() {
                    PopNationDayCallbackEvent(jsonString);
                }
            });
            new XPopup.Builder(H5Activity.this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .setPopupCallback(new XPopupCallback() {
                        @Override
                        public void onCreated() {

                        }

                        @Override
                        public void beforeShow() {

                        }

                        @Override
                        public void onShow() {
                            NativeAdvertManager.getInstance().loadExpressAd(H5Activity.this, 270, new InteractionAdListener() {
                                @Override
                                public void onRenderSuccess(View view) {
                                    nationalActivityPopup.addAdvertView(view);
                                }

                                @Override
                                public void onError() {
                                    nationalActivityPopup.loadAdvertFail();
                                }
                            });
                        }

                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public boolean onBackPressed() {
                            return false;
                        }
                    })
                    .asCustom(nationalActivityPopup)
                    .show();

        });
    }

    //检查更新
    @JavascriptInterface
    public void checkUpgrade() {
        runOnUiThread(Beta::checkUpgrade);
    }

    @JavascriptInterface
    public void PopViewEvent(String jsonString) {
        runOnUiThread(() -> {
            Activity activity = this;
            Giftjson result = ParseJsonUtils.parseData(jsonString + "", Giftjson.class);
            CommonPopup giftSignPopup = new CommonPopup(this, result.getTitle(), result.getSubTitle(), result.getValue() + "", result.getUiType() + "");
            new XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .setPopupCallback(new XPopupCallback() {
                        @Override
                        public void onCreated() {

                        }

                        @Override
                        public void beforeShow() {

                        }

                        @Override
                        public void onShow() {
                            NativeAdvertManager.getInstance().loadExpressAd(activity, new InteractionAdListener() {
                                @Override
                                public void onRenderSuccess(View view) {
                                    giftSignPopup.addAdvertView(view);
                                }

                                @Override
                                public void onError() {
                                    giftSignPopup.loadAdvertFail();
                                }
                            });
                        }

                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public boolean onBackPressed() {
                            return false;
                        }
                    })
                    .asCustom(giftSignPopup)
                    .show();
            giftSignPopup.setPopupListener(new OnPopupListener() {
                @Override
                public void onNext() {
                    popViewCallbackEvent(result.getPopType());
                }

                @Override
                public void onClose() {
                }
            });
        });
    }

    //国庆回传
    private void PopNationDayCallbackEvent(String jsonString) {
        quickCallJs("PopNationDayCallbackEvent", null, jsonString);
    }

    private void popViewCallbackEvent(String popType) {
        quickCallJs("PopViewCallbackEvent", null, popType);
    }

    private void quickCallJs(String method, ValueCallback<String> callback, String...
            params) {
        StringBuilder sb = new StringBuilder();
        sb.append("javascript:" + method);
        if (params == null || params.length == 0) {
            sb.append("()");
        } else {
            sb.append("(").append(WebUtils.concat(params)).append(")");
        }
        callJs(sb.toString(), callback);
    }

    private void callJs(String js, final ValueCallback<String> callback) {
        if (webview != null) {
            webview.evaluateJavascript(js, null);
        }
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(H5Activity.this, "收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                if (platform != SHARE_MEDIA.MORE
                        && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST
                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    Toast.makeText(H5Activity.this, "分享成功啦", Toast.LENGTH_SHORT).show();
                }
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST
                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                Toast.makeText(H5Activity.this, "分享失败啦", Toast.LENGTH_SHORT).show();
            }
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
//            Toast.makeText(H5Activity.this, "分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    private boolean isRewarding = false;

    //激励视频
    //"type": String, // "PUNCH":会员签到, "TASK" :限次激励, "SHARE_VIDEO"：分享任务,"NEW_WITHDRAW":新人提现
    // "FIRST_GET" :首次观看,  "LIKE" :点赞视频, "BIND_WECHAT"：绑定微信, "OPEN_NOTIFICATION"：开启推送, "TIME_LIMIT"：限时登录, "APPRAISE"：长豆评价
    @JavascriptInterface
    public void rewardedAdvert(String type) {
        callRewardedAdvert(type, "");
    }

    @JavascriptInterface
    public void rewardedAdvertEvent(String type, String reportId) {
        callRewardedAdvert(type, reportId);
    }

    private void callRewardedAdvert(String type, String reportId) {
        runOnUiThread(() -> {
            if (isRewarding) {
                return;
            }
            isRewarding = true;
            if (webview != null) {
                webview.postDelayed(() -> isRewarding = false, 1500);
            } else {
                isRewarding = false;
            }
            if (!ToLogin()) {
                mAdvertType = type;
                RewardAdvertManager.getInstance().showAdvert(H5Activity.this, mAdvertType, reportId, new OnRewardListener() {
                    @Override
                    public void onAdClose() {
                        rewardedAdvertResult("true");
                    }

                    @Override
                    public void onAdClick() {

                    }

                    @Override
                    public void onVideoComplete() {

                    }

                    @Override
                    public void onVideoError() {
                        rewardedAdvertResult("false");
                    }
                });

            }
        });
    }

    //是否不再提醒
    @JavascriptInterface
    public boolean isCalendarReminded() {
        return CalendarManager.getInstance().isCalendarReminded();
    }

    @JavascriptInterface
    public void setCalendarReminded() {
        CalendarManager.getInstance().setCalendarReminded(true);
    }

    @JavascriptInterface
    public void reportAdvertAction(int pageId, String action, String note) {
        runOnUiThread(() -> TrackManager.getInstance().reportAdvertAction(pageId, action, note));
    }

    // 开启提醒规则
    @JavascriptInterface
    public void startCalendarRemind() {
        CalendarManager.getInstance().startCalendarRemind(this);
    }

    //"type": String, // "PUNCH":会员签到, "TASK" :限次激励, "SHARE_VIDEO"：分享任务,
    // "FIRST_GET" :首次观看,  "LIKE" :点赞视频, "BIND_WECHAT"：绑定微信, "OPEN_NOTIFICATION"：开启推送, "TIME_LIMIT"：限时登录, "APPRAISE"：长豆评价
    //result: true 成功 false：失败
    private void rewardedAdvertResult(String result) {
        quickCallJs("rewardedAdvertResult", null, mAdvertType, result);
    }


    public void getDomain(SHARE_MEDIA type, String json) {
        String shareTitle = getString(R.string.shareTitle);
        String shareDes = getString(R.string.smallTitle);
        try {
            ShareBean shareBean = ParseJsonUtils.parseData(json + "", ShareBean.class);
            if (shareBean != null) {
                if (!TextUtils.isEmpty(shareBean.getTitle())) {
                    shareTitle = shareBean.getTitle();
                }
                if (!TextUtils.isEmpty(shareBean.getDes())) {
                    shareDes = shareBean.getDes();
                }
            }
        } catch (Exception ignored) {

        }
        String finalShareTitle = shareTitle;
        String finalShareDes = shareDes;
        HttpData.getInstance().domain(new ACallback<BaseData>() {
            @Override
            public void onSuccess(BaseData data) {
                if (data.getCode() == 200 && data.getData() != null) {
                    UMWeb web = new UMWeb(((String) data.getData()) + "/#/shareqq" + "?code=" + Store.getInstance().getAgent_code() + "&nickname=" + Store.getInstance().getUserName());//网址
                    web.setTitle(finalShareTitle);//标题
                    web.setThumb(new UMImage(H5Activity.this, R.mipmap.share_icon));  //缩略图
                    web.setDescription(finalShareDes);//描述
                    new ShareAction(H5Activity.this)
                            .setPlatform(type)//传入平台
                            .withMedia(web)
                            .setCallback(shareListener)
                            .share();
                } else {
                    UMWeb web = new UMWeb(Constants.H5_YYB);//网址
                    web.setTitle(finalShareTitle);//标题
                    web.setThumb(new UMImage(H5Activity.this, R.mipmap.share_icon));  //缩略图
                    web.setDescription(finalShareDes);//描述
                    new ShareAction(H5Activity.this)
                            .setPlatform(type)//传入平台
                            .withMedia(web)
                            .setCallback(shareListener)
                            .share();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                UMWeb web = new UMWeb(Constants.H5_YYB);//网址
                web.setTitle(finalShareTitle);//标题
                web.setThumb(new UMImage(H5Activity.this, R.mipmap.share_icon));  //缩略图
                web.setDescription(finalShareDes);//描述
                new ShareAction(H5Activity.this)
                        .setPlatform(type)//传入平台
                        .withMedia(web)
                        .setCallback(shareListener)
                        .share();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Store.getInstance().getPrivacy()) {
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        }
        if (requestCode == CommonConstants.MAIN) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
        } else if (requestCode == BING) {
            if (resultCode == RESULT_OK) {
                finish();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webview.canGoBack()) {
                webview.goBack(); //goBack()表示返回WebView的上一页面
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return false;
    }

    @Override
    public void onBackPressedSupport() {
        if (intent.getBooleanExtra("Refresh", false)) {
            setResult(RESULT_OK);
        }
        super.onBackPressedSupport();
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        LoadDialogManager.getInstance().dismiss();
        if (Store.getInstance().getPrivacy()) {
            UMShareAPI.get(this).release();
        }
        super.onDestroy();
    }
}
